package com.sumainfor.pc.market.service;

import com.alibaba.fastjson.JSONObject;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.util.*;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

/**
 * @author Meng
 * @ClassName MeterBillService
 * @date 2019/12/5 11:34
 * @description: TODO
 */
@Service
public class MeterBillService implements Serializable {


    @Autowired
    RedisUtils redisUtils;

    /**
     * 签约修改智能设备
     * @param params
     * @return
     */
    public JsonResult GetMeterBill(Map<String,Object> params){

        JsonResult result = new JsonResult();
        //如果整租智且电表为蜂电那么修改所有房间为后付费模式,
        Map<String,Object> smartMeterMap = (Map<String, Object>) params.get("smartMeterMap");
         if (smartMeterMap!=null){

        if (smartMeterMap.get("list") == null || smartMeterMap.get("Intelligent") == null) {
            return result.putFailed("服务器繁忙");
        }
        System.out.println("接收到的参数:" + params);
        //保存匹配到第三方返回的电表当前读数
        List<Map<String, Object>> InteDeviceBeeList = (List<Map<String, Object>>) smartMeterMap.get("list");
        //Intelligent 智能设备供应商     0.蜂电   1.大华   2.科技侠   3.果加
        if (smartMeterMap.get("Intelligent").toString().equals("0")) {
            String InteDeviceBeeToken = redisUtils.get("InteDeviceBeeToken");
            System.out.println(InteDeviceBeeToken);
            //如果获取不到就重新登录
            if (InteDeviceBeeToken == null) {
                Map<String, Object> loginMap = new HashMap<String, Object>();
                loginMap.put("version", UUIDUtils.generateShortUuid());//业务流水号UUID
                loginMap.put("appid", InteDeviceBeeConfig.APP_ID);
                //登录获取token
                loginMap = InteDeviceBeeUtil.userLogin(InteDeviceBeeConfig.USERID, InteDeviceBeeConfig.PASS, loginMap);
                if (loginMap.get("Code").toString().equals("0")) {//0 状态码 请求成功
                    InteDeviceBeeToken = loginMap.get("Expand").toString();
                    //token存到redis中 蜂电token 有效时长一小时
                    redisUtils.set("InteDeviceBeeToken", InteDeviceBeeToken, 3600);
                    System.out.println(InteDeviceBeeToken);
                } else {
                    return result.putFailed("token获取失败");
                }
            }

            //智能电表必定是每个房间都有一个电表，用房间集合的长度初始化智能电表设备编号数组
            List<String> InteList = new ArrayList<String>();
            Map<String, Object> headMap = new HashMap<String, Object>();
            headMap.put("uid", InteDeviceBeeConfig.UID);//唐巢在蜂电用户ID
            headMap.put("token", InteDeviceBeeToken);//访问令牌
            headMap.put("version", "0116010101");//版本号默认0116010101
            for (int i = 0; i < InteDeviceBeeList.size(); i++) {
                Map<String, Object> map1 = InteDeviceBeeList.get(i);
                if (map1.get("Identifier") != null) {
                    InteList.add(map1.get("Identifier").toString());
                }
            }
            //蜂电返回的参数
            Map<String, Object> InteDataMap = InteDeviceBeeUtil.deviceAmmeterPcode(InteList, headMap);
            if (InteDataMap.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                //电表数组
                List<Map<String, Object>> InteDataList = (List<Map<String, Object>>) InteDataMap.get("Data");
                for (Map<String, Object> map1 : InteDeviceBeeList) {
                    if (map1.get("Identifier") != null) {
                        for (Map<String, Object> map2 : InteDataList) {
                            if (map2.get("Ccode") != null) {
                                if (map1.get("Identifier").toString().equals(map2.get("Pcode").toString())) {
                                    map1.put("Uuid", map2.get("Uuid"));
                                }
                            }
                        }
                    }
                }
                System.out.println(InteDeviceBeeList);

                if (MapUtils.getInteger(params, "ProOperaType") == 2) {//整租,并且房间智能电表为蜂电,修改模式为后付费,并且办理蜂电电表入住
                    //蜂电电表入住
                    JSONObject bodyJson = new JSONObject();
                    bodyJson.put("phone", "13183302095");
                    bodyJson.put("name", "周哥");
                    for (Map<String, Object> map1 : InteDeviceBeeList) {
                        Map<String, Object> InteDataMaps = InteDeviceBeeUtil.deviceAmmeterStayroom(MapUtils.getString(map1, "Uuid"), headMap, bodyJson);
                        if (!InteDataMaps.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                            return result.putFailed("第三方服务器繁忙");
                        } else {
                            //智能设备UUID  模式0是后付费，1是预付费 请求头部信息
                            //修改房间电表的付费模式
                            Map<String, Object> a1 = InteDeviceBeeUtil.deviceAmmeterPaymode(map1.get("Uuid").toString(), "0", headMap);
                            if (!a1.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                                return result.putFailed("第三方服务器繁忙");
                            }
                            System.out.println(a1);
                        }
                    }
                } else {//合租
                    //蜂电电表入住
                    JSONObject bodyJson = new JSONObject();
                    bodyJson.put("phone", "13183302095");
                    bodyJson.put("name", "周哥");
                    String Hous = MapUtils.getString(params, "HouInfoId");
                    String HouLast = Hous.substring(Hous.length() - 1, Hous.length());
                    for (Map<String, Object> map1 : InteDeviceBeeList) {
                        String HouConName = MapUtils.getString(map1, "HouConName");
                        String HouConLast = HouConName.substring(HouConName.length() - 1, HouConName.length());
                        if (HouLast.equals(HouConLast)) {
                            Map<String, Object> InteDataMaps = InteDeviceBeeUtil.deviceAmmeterStayroom(MapUtils.getString(map1, "Uuid"), headMap, bodyJson);
                            if (!InteDataMaps.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                                return result.putFailed("第三方服务器繁忙");
                            }else{//修改单价

                              Map<String,Object>  pricemap =  InteDeviceBeeUtil.deviceAmmeterPrice(MapUtils.getString(map1, "Uuid"),MapUtils.getString(params,"value"),headMap);
                                if (!pricemap.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                                    return result.putFailed("第三方服务器繁忙");
                                }

                            }
                        }

                    }

                }
            } else {
                return result.putFailed("第三方服务器繁忙");
            }

        }   else if (smartMeterMap.get("Intelligent").toString().equals("1")) {//大华
                String InteDaHuaToken = redisUtils.get("InteDaHuaToken");
                //如果获取不到就重新登录
                if (InteDaHuaToken == null) {
                    /*获取token*/
                    Map<String, Object> DaParams = new HashMap<String, Object>();
                    DaParams.put("pw", InteDeviceDaHuaConfig.PW);
                    DaParams.put("userName", InteDeviceDaHuaConfig.USERNAME);
                    DaParams = InteDeviceDaHuaUtil.getToken(DaParams);
                    if (DaParams.get("code") != null && DaParams.get("code").toString().equals("1")) {//1 状态码 请求成功
                        InteDaHuaToken = DaParams.get("data").toString();
                        //token有效期2个小时，所有接口Code=0 ，token失效 需要重新获取
                        redisUtils.set("InteDaHuaToken", InteDaHuaToken, 3600 * 2);
                        System.out.println(InteDaHuaToken);
                    } else {
                        return result.putFailed("token获取失败");
                    }
                }

                Map<String, Object> tokenMap = new HashMap<>();
                tokenMap.put("token", InteDaHuaToken);

                if (MapUtils.getInteger(params, "ProOperaType") == 2) {//整租
                    for (Map<String, Object> ceshiMap : InteDeviceBeeList) {
                        JSONObject bodyJson = new JSONObject();
                        bodyJson.put("meter_id", ceshiMap.get("Identifier"));
                        bodyJson.put("tra_id", Calendar.getInstance().getTimeInMillis());
                        bodyJson.put("token", InteDaHuaToken);

                        Map<String, Object> getParams = InteDeviceDaHuaUtil.clearIntefers(tokenMap, bodyJson);
                        if (!(getParams.get("code") != null && getParams.get("code").toString().equals("1"))) {//0 状态码 请求成功
                            return result.putFailed("第三方服务器繁忙");
                        }
                    }
                } else {//表示合租,只用清空自己房间的电表余额

                    String Hous = MapUtils.getString(params, "HouInfoId");
                    String HouLast = Hous.substring(Hous.length() - 1, Hous.length());

                    for (Map<String, Object> ceshiMap : InteDeviceBeeList) {
                        String HouConName = MapUtils.getString(ceshiMap, "HouConName");
                        String HouConLast = HouConName.substring(HouConName.length() - 1, HouConName.length());

                        if (HouLast.equals(HouConLast)) {

                            JSONObject bodyJson = new JSONObject();
                            bodyJson.put("meter_id", ceshiMap.get("Identifier"));
                            bodyJson.put("tra_id", Calendar.getInstance().getTimeInMillis());
                            bodyJson.put("token", InteDaHuaToken);
                            Map<String, Object> getParams = InteDeviceDaHuaUtil.clearIntefers(tokenMap, bodyJson);
                            if (!(getParams.get("code") != null && getParams.get("code").toString().equals("1"))) {//0 状态码 请求成功
                                return result.putFailed("第三方服务器繁忙");
                            }
                        }
                    }
                }
            }
             return  result.putSuccess("修改智能设备成功");

        }else {

             return result.putSuccess("服务器繁忙");
         }
    }



    public JsonResult GatWithOut(Map<String,Object> params){

        JsonResult result = new JsonResult();
        //智能电表的数组
        List<Map<String,Object>> InteDeviceList=(List<Map<String,Object>>)params.get("InteDeviceList");
        System.out.println(InteDeviceList);
        //如果智能电表数组不为空的就去执行大华or蜂电的退租操作
        if (InteDeviceList.size()>0){
            //智能设备供应商     0.蜂电   1.大华   2.科技侠   3.果加
            if (params.get("ifIntelligentDevice").toString().equals("0")){
                String InteDeviceBeeToken=redisUtils.get("InteDeviceBeeToken");
                //如果获取不到就重新登录
                if (InteDeviceBeeToken==null) {
                    Map<String, Object> tokenMap = new HashMap<String, Object>();
                    params.put("version","0116010101");//版本号 默认 0116010101
                    params.put("appid", InteDeviceBeeConfig.APP_ID);
                    tokenMap=InteDeviceBeeUtil.userLogin(InteDeviceBeeConfig.USERID, InteDeviceBeeConfig.PASS,params);
                    System.out.println("tokenMap："+tokenMap);
                    if (tokenMap.get("Code").toString().equals("0")) {
                        InteDeviceBeeToken = tokenMap.get("Expand").toString();
                        //token存到redis中 有效时长一个小时
                        redisUtils.set("InteDeviceBeeToken", InteDeviceBeeToken,3600);
                    } else {
                        return result.putFailed("token获取失败");
                    }
                }
                //智能电表必定是每个房间都有一个电表，用房间集合的长度初始化智能电表设备编号数组
                List<String> InteList = new ArrayList<String>();
                Map<String, Object> headMap = new HashMap<String, Object>();
                headMap.put("uid", InteDeviceBeeConfig.UID);//唐巢在蜂电用户ID
                headMap.put("token", InteDeviceBeeToken);//访问令牌
                headMap.put("version", "0116010101");//版本号默认0116010101
                for (int i = 0; i < InteDeviceList.size(); i++) {
                    Map<String, Object> map1 = InteDeviceList.get(i);
                    if (map1.get("Identifier") != null) {
                        InteList.add(map1.get("Identifier").toString());
                    }
                }
                //蜂电返回的参数
                Map<String, Object> InteDataMap = InteDeviceBeeUtil.deviceAmmeterPcode(InteList, headMap);

                if (InteDataMap.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                    //电表数组
                    List<Map<String, Object>> InteDataList = (List<Map<String, Object>>) InteDataMap.get("Data");
                    for (Map<String, Object> map1 : InteDeviceList) {
                        if (map1.get("Identifier") != null) {
                            for (Map<String, Object> map2 : InteDataList) {
                                if (map2.get("Ccode") != null) {
                                    if (map1.get("Identifier").toString().equals(map2.get("Pcode").toString())) {
                                        map1.put("Uuid", map2.get("Uuid"));
                                    }
                                }
                            }
                        }
                    }
                    System.out.println(InteDeviceList);


                    if (MapUtils.getInteger(params, "ProOperaType") == 2) {//整租,并且房间智能电表为蜂电,修改模式为预付费
                        for (Map<String, Object> map1 : InteDeviceList) {
                            Map<String, Object> a1 = InteDeviceBeeUtil.deviceAmmeterPaymode(map1.get("Uuid").toString(), "1", headMap);
                            if (!a1.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                                return result.putFailed("第三方服务器繁忙");
                            }
                        }
                    }

                }else {
                    return result.putFailed("第三方服务器繁忙");
                }

            } else if (params.get("ifIntelligentDevice").toString().equals("1")) {//大华
                String InteDaHuaToken = redisUtils.get("InteDaHuaToken");
                //如果获取不到就重新登录
                if (InteDaHuaToken == null) {
                    /*获取token*/
                    Map<String, Object> DaParams = new HashMap<String, Object>();
                    DaParams.put("pw", InteDeviceDaHuaConfig.PW);
                    DaParams.put("userName", InteDeviceDaHuaConfig.USERNAME);
                    DaParams = InteDeviceDaHuaUtil.getToken(DaParams);
                    if (DaParams.get("code") != null && DaParams.get("code").toString().equals("1")) {//1 状态码 请求成功
                        InteDaHuaToken = DaParams.get("data").toString();
                        //token有效期2个小时，所有接口Code=0 ，token失效 需要重新获取
                        redisUtils.set("InteDaHuaToken", InteDaHuaToken, 3600 * 2);
                        System.out.println(InteDaHuaToken);
                    } else {
                        return result.putFailed("token获取失败");
                    }
                }

                Map<String, Object> tokenMap = new HashMap<>();
                tokenMap.put("token", InteDaHuaToken);

                if (MapUtils.getInteger(params, "ProOperaType") == 2) {//整租
                    for (Map<String, Object> ceshiMap : InteDeviceList) {
                        com.alibaba.fastjson.JSONObject bodyJson = new com.alibaba.fastjson.JSONObject();
                        bodyJson.put("meter_id", ceshiMap.get("Identifier"));
                        bodyJson.put("tra_id", Calendar.getInstance().getTimeInMillis());
                        bodyJson.put("token", InteDaHuaToken);

                        Map<String, Object> getParams = InteDeviceDaHuaUtil.clearIntefers(tokenMap, bodyJson);
                        if (!(getParams.get("code") != null && getParams.get("code").toString().equals("1"))) {//0 状态码 请求成功
                            return result.putFailed("第三方服务器繁忙");
                        }
                    }
                } else {//表示合租,只用清空自己房间的电表余额

                    String Hous = MapUtils.getString(params, "HouInfoId");
                    String HouLast = Hous.substring(Hous.length() - 1, Hous.length());

                    for (Map<String, Object> ceshiMap : InteDeviceList) {
                        String HouConName = MapUtils.getString(ceshiMap, "HouConName");
                        String HouConLast = HouConName.substring(HouConName.length() - 1, HouConName.length());

                        if (HouLast.equals(HouConLast)) {

                            com.alibaba.fastjson.JSONObject bodyJson = new com.alibaba.fastjson.JSONObject();
                            bodyJson.put("meter_id", ceshiMap.get("Identifier"));
                            bodyJson.put("tra_id", Calendar.getInstance().getTimeInMillis());
                            bodyJson.put("token", InteDaHuaToken);
                            Map<String, Object> getParams = InteDeviceDaHuaUtil.clearIntefers(tokenMap, bodyJson);
                            if (!(getParams.get("code") != null && getParams.get("code").toString().equals("1"))) {//0 状态码 请求成功
                                return result.putFailed("第三方服务器繁忙");
                            }
                        }
                    }
                }
            }
            return result.put(InteDeviceList);
        }else{
            return result.putFailed("第三方服务器繁忙");
        }

    }


}
